

#include "CGame.h"
#include "CMainMenuState.h"
#include "IGameState.h"

CGame::CGame(void)
{
	IGameState* m_pCurrentState = NULL;
	m_pD3D	= NULL;
	m_pDI	= NULL;
	m_pDS	= NULL;
	m_pTM	= NULL;
	m_pWM	= NULL;
	m_nImageID = -1;
	m_nSoundID = -1;
}

CGame::~CGame(void)
{
}

CGame* CGame::GetInstance(void)
{
	static CGame instance;
	return &instance;
}
void CGame::Initialize(HWND hWnd, HINSTANCE hInstance, int nScreenWidth, int nScreenHeight, bool bIsWindowed)
{
	//	Get pointers to SGD singletons
	m_pD3D	= CSGD_Direct3D::GetInstance();
	m_pDI	= CSGD_DirectInput::GetInstance();
	m_pDS	= CSGD_DirectSound::GetInstance();
	m_pTM	= CSGD_TextureManager::GetInstance();
	m_pWM	= CSGD_WaveManager::GetInstance();

	//	Initialize SGD singletons
	m_pD3D->InitDirect3D(hWnd, nScreenWidth, nScreenHeight, bIsWindowed);
	m_pDI->InitDirectInput(hWnd, hInstance,DI_KEYBOARD | DI_MOUSE);
	m_pDS->InitDirectSound(hWnd);
	m_pTM->InitTextureManager(m_pD3D->GetDirect3DDevice(), m_pD3D->GetSprite());
	m_pWM->InitWaveManager(hWnd, m_pDS->GetDSObject());
	
	//	 load common assest
	//m_nImageID = m_pTM->LoadTexture("resource/SGD_ship.bmp");
	//m_nSoundID = m_pWM->LoadWave("resource/SGD_sfx1.wav");
	
	m_nMusicVolume = 50;
	m_nSFXVolume = 50;
	m_nMusicPanning = 0;
	m_nScreenWidth = nScreenWidth;
    m_nScreenHeight = nScreenHeight;
	ChangeState(CMainMenuState::GetInstance());
	bIsWindowed = true;

}

void CGame::Shutdown(void)
{
	//	Shutdown in the opposite orde i acquired in:

	//	Safe way
	if(m_pWM)
	{
		m_pWM->ShutdownWaveManager();
		m_pWM = NULL;
	}
	if(m_pTM)
	{
		m_pTM->ShutdownTextureManager();
		m_pTM = NULL;
	}
	if(m_pDS)
	{
		m_pDS->ShutdownDirectSound();
		m_pDS = NULL;
	}
	if(m_pDI)
	{
		m_pDI->ShutdownDirectInput();
		m_pDI = NULL;
	}
	if(m_pD3D)
	{
		m_pD3D->ShutdownDirect3D();
		m_pD3D = NULL;
	}
}
bool CGame::Main(void)
{
	//	3 Steps during execution:
	//	Input
	//m_pDI->ReadDevices();	//	should be called ONLY once a frame.
	GetInput();
	m_pCurrentState->Input();

	

	//	Update
	//m_pWM->Update();	//	clean up excess copies of sounds.
	m_pCurrentState->Update();
	

	//	Render
	m_pCurrentState->Render();

	return true;
}

void CGame::ChangeState(IGameState* NewState)
{
	if(m_pCurrentState)
		m_pCurrentState->Exit();

	m_pCurrentState = NewState;

	if(m_pCurrentState)
		m_pCurrentState->Enter();
}


void CGame::GetInput()
{
	m_pDI->ReadDevices();

	if (m_pDI->KeyPressed(DIK_RETURN) && (m_pDI->KeyDown(DIK_LMENU) || m_pDI->KeyDown(DIK_RMENU)))
	{
		m_bIsWindowed = !m_bIsWindowed;
		m_pD3D->ChangeDisplayParam(m_nScreenWidth, m_nScreenHeight, m_bIsWindowed);
	}

	
}